<!DOCTYPE html>
<html lang="zh-CN" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 上述3个meta标签*必须*放在最前面，任何其他内容都*必须*跟随其后！ -->
    <title>订阅签到信息</title>

    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

    <script src="https://cdn.bootcss.com/vue/2.5.13/vue.js"></script>
    <script src="https://cdn.bootcss.com/vue-resource/1.3.4/vue-resource.min.js"></script>
    <style type="text/css">
        body {
            min-height: 2000px;
            padding-top: 70px;
        }
    </style>
    <script src="static/js/app.js"></script>
</head>
<body>
<div id="wechat_app" class="container">


    <div class="container">
        <div class="input-group">
            <span class="input-group-addon" id="search-ship-key-addon">要订阅的船舶:</span>
            <input type="text" class="form-control" id="search-ship-key" aria-describedby="search-ship-key-addon"
                   placeholder="请输入英文船名" v-model="search">
        </div>
        <div class="jumbotron" v-if="searchShips.length > 0">
            <ul class="nav nav-pills nav-stacked">
                <li role="presentation" v-for="(searchShip,index) in searchShips">
                    <div class="input-group">
                        <span class="form-control">{{searchShip.shipName}}</span>
                        <div class="input-group-btn">
                            <button type="button" class="btn btn-default"
                                    v-on:click="subscribeEvent(searchShip,index)">
                                {{ searchShip.subscribeState == 0 ? "订阅":"取消订阅"}}
                            </button>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </div><!-- /.content -->

    <div class="modal fade bs-example-modal-sm" id="subscribeModal"
         tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" style="top:100px;">
        <div class="modal-dialog modal-sm" role="document">
            <div class="modal-content">
                <!-- 修改订阅邮箱 -->
                <div class="input-group">
                    <span class="input-group-addon">订阅邮箱:</span>
                    <input type="text" class="form-control" placeholder="订阅邮箱" v-model="receiver">
                    <span class="input-group-btn">
                    <button class="btn btn-default" type="button" v-on:click="subscribe()">确定</button>
                </span>
                </div>
            </div>
        </div>
    </div><!-- /.modal -->
</div>
</body>
<script>

    new Vue({
        el: '#wechat_app',
        data: {
            wechat_config: {APP_ID: "wx751d208200afe9d0", code: "", state: "", access_token: ""},//env:wx751d208200afe9d0
            remote_api: "http://api.inuorui.com/",
            //remote_api: "http://127.0.0.1:8787/",
            service_api: "http://wechat.inuorui.com/api/",
            //service_api: "http://127.0.0.1:17170/",
            chartShips: [],
            search: '',
            receiver: '',//todo:openUser的邮箱
            currentShip: {shipName: '', licenceId: '', subscribeId: "", index: ""},
            userSubscriptions: [],
            userInfo: {openid: '', headimgurl: ''},
            emailRE: /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
        },
        beforeMount: function () {
            var _this = this;
            new Promise(function (resolve, reject) {
                console.log("init_wechat");
                _this.init_wechat(resolve, reject);
            }).then(function (val) {
                console.log("request_userInfo");
                new Promise(function (resolve, reject) {
                    _this.request_userInfo(resolve, reject)
                }).then(function (val) {
                    console.log("marge data..");
                    Promise.all([
                        new Promise(function (resolve, reject) {
                            _this.queryShips(resolve, reject);
                        }),
                        new Promise(function (resolve, reject) {
                            _this.userSubscription(resolve, reject);
                        })
                    ])
                        .then(function (arr) {
                            console.log(arr);//[1,2,3]
                            _this.margeSubscribeInfo();
                        });
                });
            })
        },
        computed: {
            searchShips: function () {
                var search = this.search;
                if (search) {
                    return this.chartShips.filter(function (data) {
                        return Object.keys(data).some(function (key) {
                            return String(data[key]).toLowerCase().indexOf(search) > -1
                        })
                    })
                } else {
                    return [];
                }
            }
        },
        methods: {
            queryShips: function (resolve, reject) {
                var url = this.remote_api + "chart/ships";
                this.$http.get(url).then(function (res) {
                    console.log(res);
                    var data = res.body;
                    if (data.reCode === 1000) {
                        console.log("可用船舶查询成功");
                        this.chartShips = data.reData;
                        resolve(this.chartShips);
                    } else {
                        alert("可用船舶查询失败：" + data.reMsg);
                        reject("可用船舶查询失败：" + data.reMsg);
                    }
                }).catch(function (err) {
                    console.log(err)
                    reject("服务器异常");
                })
            },
            subscribeEvent: function (selectedShip, shipIndex) {
                console.log("subscribeEvent:");
                console.log(selectedShip);
                this.currentShip = selectedShip;
                this.currentShip.index = shipIndex;
                if (selectedShip.subscribeState == 0) {
                    $('#subscribeModal').modal('show');
                } else {
                    this.unSubscribe();
                }
            },
            subscribe: function () {
                console.log(this.currentShip);
                var isValidEmail = this.emailRE.test(this.receiver);
                console.log("vaild:" + isValidEmail);
                if (!isValidEmail) {
                    alert("请输入合法的邮箱地址");
                    return;
                }
                var obj = {
                    openId: this.userInfo.openid,
                    serviceType: "CHART_UPDATE",
                    serviceId: this.currentShip.licenceId,
                    receiver: this.receiver
                };
                var url = this.service_api + "subscription/subscribe";
                this.$http.post(url, obj).then(function (res) {
                    console.log(res);
                    var data = res.body;
                    if (data.reCode === 1000) {
                        alert("订阅成功");
                        console.log("index:" + this.currentShip.index);
//                        this.chartShips[this.currentShip.index].subscribeState = 1;
                        //todo:userSubscriptions 增减
                        var _this = this;
                        new Promise(function (resolve, reject) {
                            _this.userSubscription(resolve, reject);
                        }).then(function () {
                            _this.margeSubscribeInfo();
                        });
                    } else {
                        alert("订阅失败：" + data.reMsg);
                    }
                }).catch(function (err) {
                    console.log(err)
                });
                $('#subscribeModal').modal('hide');
            },
            unSubscribe: function () {

                var url = this.service_api + "subscription/unSubscribe?subscribeId=" + this.currentShip.subscribeId;
                this.$http.get(url).then(function (res) {
                    console.log(res);
                    var data = res.body;
                    if (data.reCode === 1000) {
                        alert("取消订阅成功");
                        console.log("index:" + this.currentShip.index);
//                        this.chartShips[this.currentShip.index].subscribeState = 0;
                        //todo:userSubscriptions 增减
                        var _this = this;
                        new Promise(function (resolve, reject) {
                            _this.userSubscription(resolve, reject);
                        }).then(function () {
                            _this.margeSubscribeInfo();
                        });
                    } else {
                        alert("取消订阅失败：" + data.reMsg);
                    }
                }).catch(function (err) {
                    console.log(err)
                });
            },
            userSubscription: function (resolve, reject) {
                console.log('ready..');
                var url = this.service_api + "subscription?openId=" + this.userInfo.openid;
                this.$http.get(url).then(function (res) {
                    console.log(res);
                    var data = res.body;
                    if (data.reCode === 1000) {
                        console.log("订阅信息查询成功");
                        this.userSubscriptions = data.reData;
                        if (resolve) {
                            resolve(this.userSubscriptions);
                        }
                    } else {
                        alert("订阅信息查询失败：" + data.reMsg);
                        if (reject) {
                            reject("订阅信息查询失败：" + data.reMsg);
                        }
                    }
                }).catch(function (err) {
                    console.log(err)
                    if (reject) {
                        reject("服务器异常");
                    }
                })
            },
            setSubscribeInfo: function (ship) {
                Vue.set(ship, 'subscribeId', "");
                Vue.set(ship, 'subscribeState', 0);
                this.userSubscriptions.forEach(function (element) {
                    if (element.serviceId === ship.licenceId) {
                        console.log("变更为：取消订阅");
                        Vue.set(ship, 'subscribeId', element.id);
                        Vue.set(ship, 'subscribeState', 1);
                        return;
                    }
                })
            },
            margeSubscribeInfo: function () {
                var _this = this;
                this.chartShips.forEach(function (ship) {
                    _this.setSubscribeInfo(ship);
                })
            },
            request_userInfo: function (resolve, reject) {
                var url = this.service_api + "user/info?accessToken="
                    + this.wechat_config.access_token + "&openId=" + this.wechat_config.openid;
                this.$http.get(url).then(function (res) {
                    console.log(res);
                    var data = res.body;
                    if (data.reCode == 1000) {
                        this.userInfo = data.reData;
                        console.log("用户信息获取成功");
                        resolve(this.userInfo);
                    } else {
                        alert("用户信息获取失败：" + data.reMsg);
                        reject("用户信息获取失败");
                    }
                }).catch(function (err) {
                    console.log(err)
                    reject("服务器异常");
                })
            },
            request_accessToken: function (resolve, reject) {
                var url = this.service_api + "user/accessToken?appId=" + this.wechat_config.APP_ID
                    + "&code=" + this.wechat_config.code;
                this.$http.get(url).then(function (res) {
                    console.log(res);
                    var data = res.body;
                    if (data.reCode === 1000) {
                        this.wechat_config = data.reData;
                        resolve(this.wechat_config);
                    } else {
                        alert("服务异常");
                        reject("服务异常");
                    }
                }).catch(function (err) {
                    console.log(err)
                    reject("服务异常");
                })
            },
            init_wechat: function (resolve, reject) {
                //1. 回调后，获取当前页面的链接 eg: http://wechat.inuorui.com/?code=CODE&state=STATE
                getQueryString = function (name) {
                    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
                    var r = window.location.search.substr(1).match(reg);
                    if (r != null) {
                        return unescape(r[2]);
                    }
                    return null;
                }
                this.wechat_config.code = getQueryString("code");
                this.wechat_config.state = getQueryString("state");
                //2. 获取code后，向服务器（只能服务端获取否则有跨域问题）请求以下链接获取access_token：
                //过期时间7200
                this.request_accessToken(resolve, reject);
            }
        }
    })
</script>
</html>